/**
 *
 */
package org.jim.server.demo;

import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImPacket;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.WebPropUtil;
import org.jim.server.JimServer;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.ChatReqHandler;
import org.jim.server.command.handler.JoinGroupReqHandler;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.command.handler.MessageReqHandler;
import org.jim.server.config.ImServerConfig;
import org.jim.server.config.PropertyImServerConfigBuilder;
import org.jim.server.demo.listener.ImDemoGroupListener;
import org.jim.server.demo.listener.ImDemoUserListener;
import org.jim.server.demo.service.AbstactTransformHandler;
import org.jim.server.demo.service.InitHandlerMapper;
import org.jim.server.demo.service.LoginServiceProcessor;
import org.jim.server.processor.chat.DefaultAsyncChatMessageProcessor;
import org.jim.server.util.ChatKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.tio.core.ssl.SslConfig;

/**
 * IM服务端DEMO演示启动类;
 * @author WChao
 * @date 2018-04-05 23:50:25
 */
public class JIMServerStart implements ApplicationListener<ContextRefreshedEvent> {

    private static Logger log = LoggerFactory.getLogger(JIMServerStart.class);


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (WebPropUtil.start) {
            WebPropUtil.start = false;
            try {
                startJIM();
                log.info("JIM Server Start SUCCESS!");
            } catch (Exception e) {
                log.error("JIM Server Start FAILED!");
                e.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) {
//        TIT tit = new TIT();
//        tit.initHandler();
//    }

//    public static void main(String[] args) {
//        try {
//            startJIM();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void startJIM() throws Exception {
        ImServerConfig imServerConfig = new PropertyImServerConfigBuilder("config/jim.properties").build();
        //初始化SSL;(开启SSL之前,你要保证你有SSL证书哦...)
        initSsl(imServerConfig);
        //设置群组监听器，非必须，根据需要自己选择性实现;
        imServerConfig.setImGroupListener(new ImDemoGroupListener());
        //设置绑定用户监听器，非必须，根据需要自己选择性实现;
        imServerConfig.setImUserListener(new ImDemoUserListener());
        JimServer jimServer = new JimServer(imServerConfig);
//        init();
        webInit();
        jimServer.start();
//        testSendUser();
    }

    private static void webInit() {
        Object obj = InitHandlerMapper.handlerMapper.get(InitHandlerMapper.HANDLER_CONFIG);
        if (obj != null && obj instanceof AbstactTransformHandler) {
            ((AbstactTransformHandler) obj).initHandler();
        }
    }

    public static void init() {
        /*****************start 以下处理器根据业务需要自行添加与扩展，每个Command都可以添加扩展,此处为demo中处理**********************************/
        //申请进入群组处理器;
        JoinGroupReqHandler joinGroupReqHandler = CommandManager.getCommand(Command.COMMAND_JOIN_GROUP_REQ, JoinGroupReqHandler.class);
        joinGroupReqHandler.setSingleProcessor(new LoginServiceProcessor());
        //进入群组通知
        MessageReqHandler messageReqHandler = CommandManager.getCommand(Command.COMMAND_JOIN_GROUP_NOTIFY_RESP, MessageReqHandler.class);
        messageReqHandler.setSingleProcessor(new LoginServiceProcessor());
        //添加登录业务处理器;
        LoginReqHandler loginReqHandler = CommandManager.getCommand(Command.COMMAND_LOGIN_REQ, LoginReqHandler.class);
        loginReqHandler.setSingleProcessor(new LoginServiceProcessor());
        //添加用户业务聊天记录处理器，用户自己继承抽象类BaseAsyncChatMessageProcessor即可，以下为内置默认的处理器！
        ChatReqHandler chatReqHandler = CommandManager.getCommand(Command.COMMAND_CHAT_REQ, ChatReqHandler.class);
        chatReqHandler.setSingleProcessor(new DefaultAsyncChatMessageProcessor());
        /*****************end *******************************************************************************************/
    }

    private void testSendUser() {
        String msg = "{\"chatType\":2,\"cmd\":11,\"content\":\"覆盖\",\"createTime\":1637552051946,\"from\":\"1637541849251\",\"id\":\"96c76d9dbba441f7987106a9d99b3940\",\"msgType\":0,\"to\":\"1637541844306\"}";
        ChatBody chatBody = ChatKit.parseChatBody(msg);
        ImPacket chatPacket = new ImPacket(Command.COMMAND_CHAT_REQ, new RespBody(Command.COMMAND_CHAT_REQ, chatBody).toByte());
        //设置同步序列号;
        chatPacket.setSynSeq(10086);
        //私聊
        while (true) {
            JimServerAPI.sendToUser("1637541844306", chatPacket);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 开启SSL之前，你要保证你有SSL证书哦！
     * @param imServerConfig
     * @throws Exception
     */
    private static void initSsl(ImServerConfig imServerConfig) throws Exception {
        //开启SSL
        if (ImServerConfig.ON.equals(imServerConfig.getIsSSL())) {
            String keyStorePath = WebPropUtil.getPath();
            String keyStoreFile = keyStorePath;
            String trustStoreFile = keyStorePath;
            String keyStorePwd = WebPropUtil.getPasswd();
            if (StringUtils.isNotBlank(keyStoreFile) && StringUtils.isNotBlank(trustStoreFile)) {
                SslConfig sslConfig = SslConfig.forServer(keyStoreFile, trustStoreFile, keyStorePwd);
                imServerConfig.setSslConfig(sslConfig);
            }
        }
    }


}
